//import 'package:amap_base/amap_base.dart';

import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'dart:convert' as convert;

import 'package:barcode_scan/barcode_scan.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hotwork/Myapplication.dart';
import 'package:flutter_hotwork/bean/AreaBean.dart';
import 'package:flutter_hotwork/bean/BaseBean.dart';
import 'package:flutter_hotwork/homepage/BaseTitleBar.dart';
import 'package:flutter_hotwork/homepage/BaseViewBar.dart';
import 'package:flutter_hotwork/utils/DioUtils.dart';
import 'package:flutter_hotwork/utils/LogUtil.dart';
import 'package:image_picker/image_picker.dart';

import '../LoadingDialog.dart';
import '../Toast.dart';
import 'XunJianDevice2.dart';

class XunJianAreaActivity extends StatefulWidget {
  @override
  baseState createState() => new baseState();
}

class baseState extends State<XunJianAreaActivity> {

  AreaBean areaBean;
  List<File> _imagepaths = new List();
  var thisindex;

  @override
  void initState() {
    super.initState();
    DioUtils.createInstance();
    queryData();
  }
//手机号的控制器
  @override
  void dispose() {
//    _amapLocation.stopLocate();
    super.dispose();
  }
  ScrollController controller = ScrollController();
  ///接收选择的结果

  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery
        .of(context)
        .size
        .height / 800;
    double rpxw = MediaQuery
        .of(context)
        .size
        .width / 750;
    return Scaffold(
      appBar:new BaseViewBar(
          childView:
          Column(
            children: [
              new BaseTitleBar(
                "巡检区域",
                leftIcon: 'images/fanhui.png',
                rightIcon:  "",
                rightClick: () {
                  print("点击了右边干嘛啊。。。哦");
                },
                leftClick: () {
                  Navigator.of(context).pop();
                },
              )
              ,
            ],
          ),
          preferredSize: Size.fromHeight(58.0)

      ),
      body:
          Container(
          padding: EdgeInsets.only(left: 10),
          child:
          Column(
            children: [
              areaBean!=null?
              Container(
                child:
                Expanded(
                  child: (
                    genContentList(
                        areaBean.result,context, controller
                    )
                  ),
                ),


              )


                  :
              Container(),

            ],
          )


        ),
    );
  }
  genContentList(List<Area> data, BuildContext context, controller) {
    double rpx = MediaQuery
        .of(context)
        .size
        .width / 750;

    return ListView.builder(
      shrinkWrap: true,
      controller: controller,
      itemCount: data.length,
      itemBuilder: (BuildContext context, int index) {
        return
        InkWell(
          onTap:
              (){
                Navigator.push(context, MaterialPageRoute(builder: (context) {
                  MyApplication.areaId=data[index].areaId;
                  MyApplication.areaBean=data[index];
                  return new XunJianAreaDeviceActivity2();
                }));
              },
            child: Card(
          // padding: EdgeInsets.only(left: 10, right: 10, top: 0, bottom: 0),
          child:
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
//                交叉轴的布局方式，对于column来说就是水平方向的布局方式
            crossAxisAlignment: CrossAxisAlignment.center,
            //就是字child的垂直布局方向，向上还是向下
            verticalDirection: VerticalDirection.down,
            children: [
              Container(
                  height: 40,
                  width: rpx*300,
                  child:
                  Center(
                    child:
                    Text("区域名称："+data[index].areaName,
                      style: TextStyle(color: Colors.black, fontSize: 12,),
                    ),
                  )
              ),
              data[index].clocking==0?
              InkWell(
                onTap: (){
                  scan(index,data[index].areaId,data[index].inspectorId);
                },
                child:
                Container(
                    width: 50,
                    height: 20,
                    margin: EdgeInsets.only(left: 10, right: 0, top:0, bottom: 0),
                    padding:  EdgeInsets.only(left: 2, right: 2, top:0, bottom: 0),
                    decoration: BoxDecoration(
                      // border: new Border.all(color: Colors.blue, width: 0.5), // 边色与边宽度
                      color: Colors.blue, // 底色
                      borderRadius: new BorderRadius.circular((5.0)), // 圆角度
                    ),
                    child:
                    Row(
                      mainAxisAlignment:MainAxisAlignment.center,
                      children: [
                        Text("打卡",
                          style: TextStyle(color: Colors.white,fontSize: 10),
                        )

                      ],
                    )
                ),
              ): InkWell(
                onTap: (){
                },
                child:
                Container(
                    width: 50,
                    height: 20,
                    margin: EdgeInsets.only(left: 10, right: 0, top:0, bottom: 0),
                    padding:  EdgeInsets.only(left: 2, right: 2, top:0, bottom: 0),
                    decoration: BoxDecoration(
                      // border: new Border.all(color: Colors.blue, width: 0.5), // 边色与边宽度
                      color: Colors.grey, // 底色
                      borderRadius: new BorderRadius.circular((5.0)), // 圆角度
                    ),
                    child:
                    Row(
                      mainAxisAlignment:MainAxisAlignment.center,
                      children: [
                        Text("已打卡",
                          style: TextStyle(color: Colors.white,fontSize: 10),
                        )

                      ],
                    )
                ),
              ),

              data[index].doneImageUrl==null||data[index].doneImageUrl==""?
              InkWell(
                onTap: (){
                  _takePhoto();
                   thisindex = index;
                },
                child:
                Container(
                    width: 100,
                    height: 20,
                    margin: EdgeInsets.only(left: 10, right: 0, top:0, bottom: 0),
                    padding:  EdgeInsets.only(left: 2, right: 2, top:0, bottom: 0),
                    decoration: BoxDecoration(
                      // border: new Border.all(color: Colors.blue, width: 0.5), // 边色与边宽度
                      color: Colors.blue, // 底色
                      borderRadius: new BorderRadius.circular((5.0)), // 圆角度
                    ),
                    child:
                    Row(
                      mainAxisAlignment:MainAxisAlignment.center,
                      children: [
                        Text("图像记录",
                          style: TextStyle(color: Colors.white,fontSize: 10),
                        )

                      ],
                    )
                ),
              ):
              InkWell(
                onTap: (){},
                child:
                Container(
                    width: 100,
                    height: 20,
                    margin: EdgeInsets.only(left: 10, right: 0, top:0, bottom: 0),
                    padding:  EdgeInsets.only(left: 2, right: 2, top:0, bottom: 0),
                    decoration: BoxDecoration(
                      // border: new Border.all(color: Colors.blue, width: 0.5), // 边色与边宽度
                      color: Colors.grey, // 底色
                      borderRadius: new BorderRadius.circular((5.0)), // 圆角度
                    ),
                    child:
                    Row(
                      mainAxisAlignment:MainAxisAlignment.center,
                      children: [
                        Text("已完成",
                          style: TextStyle(color: Colors.white,fontSize: 10),
                        )

                      ],
                    )
                ),
              )

            ],

          ),

        ))
          ;
        // Expanded(
        //   child:
        // Flexible(
        //   child:
        // getItemContentList(data[index].focusHotUserVos,context,controller),
        // )
        // )

      },
    );
  }
  //获取区域
  void queryData() async {
    // Navigator.pop(context);
    try {
      Response response;
      response = await DioUtils.dio.get(
          DioUtils.API_PREFIX + "/checkTask/listStartTaskAllArea?checkUser="+MyApplication.loginuserinfo.userInfo.username+"&taskId="+MyApplication.nowtaskbean.id.toString());
      Map respMap = json.decode(response.data);
      areaBean = AreaBean.fromJson(respMap);
      if(null!= areaBean.result&&areaBean.result.length>0){
        MyApplication.inspacterId = areaBean.result[0].inspectorId;
      }

      setState(() {
      });
    } catch (e) {
      print('请求出错：' + e.toString());
    }
  }
  Future scan(var index,var areaId,var ispacterId) async {
    try {
      // 此处为扫码结果，barcode为二维码的内容
      String barcode = await BarcodeScanner.scan();
      print('扫码结果: '+barcode);
      uploadticket(index,barcode,areaId,ispacterId);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        // 未授予APP相机权限
        print('未授予APP相机权限');
      } else {
        // 扫码错误
        print('扫码错误: $e');
      }
    } on FormatException{
      // 进入扫码页面后未扫码就返回
      print('进入扫码页面后未扫码就返回');
    } catch (e) {
      // 扫码错误
      print('扫码错误: $e');
    }
  }
  //上传打卡点
  void uploadticket(var index,var clockInNumber,var areaId,var ispacterId) async {
    showDialog(
        context: context,
        builder: (context) {
          return new LoadingDialog();
        });
    try {
      Response response;
      response = await DioUtils.dio.get(DioUtils.API_PREFIX+"/checkTask/checkStartClock?"
          "lat="+MyApplication.bd_decrypt().latitude.toString()+
          "&lon="+MyApplication.bd_decrypt().longitude.toString()+
          "&areaId="+areaId.toString()+
          "&labelCode="+clockInNumber+
          "&checkType="+MyApplication.nowtaskbean.checkType.toString()+
          "&taskId="+MyApplication.nowtaskbean.id.toString()+
          "&inspectorId="+MyApplication.inspacterId.toString()+
          "&clockTime="+new DateTime.now().toString());

      Map respMap = json.decode(response.data);
      basebean base = basebean.fromJson(respMap);
      Navigator.pop(context);
      if(base.success){
        areaBean.result[index].clocking=1;
        LocalToast.toast(context,msg: "打卡成功");
        setState(() {
          queryData();
        });
      }else{
        LocalToast.toast(context,msg: base.message);
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      Navigator.pop(context);
      LocalToast.toast(context,msg: "打卡失败");
    }
  }
  //一键完成
  void uploadok(var index, String url) async {
    showDialog(
        context: context,
        builder: (context) {
          return new LoadingDialog();
        });
    try {

      var checkDoneDto =Map<Object,Object>();
      checkDoneDto["areaId"]=areaBean.result[thisindex].areaId.toString();
      checkDoneDto["checkType"]=MyApplication.nowtaskbean.checkType.toString();
      checkDoneDto["taskId"]=MyApplication.nowtaskbean.id.toString();
      checkDoneDto["inspectorId"]=MyApplication.inspacterId.toString();
      checkDoneDto["clockTime"]=DateTime.now().toString();
      checkDoneDto["doneImageUrl"]=url;

      Response response;
      response = await DioUtils.dio.put(DioUtils.API_PREFIX+"/checkTask/checkIsDone", data: json.encode(checkDoneDto));

      Map respMap = json.decode(response.data);
      basebean base = basebean.fromJson(respMap);
      Navigator.pop(context);
      if(base.success){
        LocalToast.toast(context,msg: "图像记录成功");
        setState(() {
          queryData();
        });
      }else{
        LocalToast.toast(context,msg: base.message);
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      Navigator.pop(context);
      LocalToast.toast(context,msg: "图像记录失败");
    }
  }

  /*拍照*/
  _takePhoto() async {
     var image = await ImagePicker.pickImage(source: ImageSource.camera);
    setState(() {
      if (null != image) {
        _imagepaths.add(image);
        _upLoadImage(image, 0);
      }
    });
  }
  //上传图片
  _upLoadImage(File imagpath, int type) async {
    String path = imagpath.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    // FormData formData = new FormData.fromMap({
    //   "file": new MultipartFile.fromFile (new File(path), name)
    // });
    FormData formdata = FormData.fromMap(
        {"file": await MultipartFile.fromFile(path, filename: name)});
    var respone = await DioUtils.dio.post<String>(
        DioUtils.API_PREFIX + "/app/upload/upLoadFile",
        data: formdata);
    if (respone.statusCode == 200) {
      Map respMap = json.decode(respone.data);
      basebean base = basebean.fromJson(respMap);
      uploadok(thisindex,base.result.toString());
    } else {
      _imagepaths.remove(imagpath);
      LocalToast.toast(context, msg: "文件过大，上传失败！");
    }
  }
}






















